import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_icons.dart';
import '../../../core/providers/discussion_hub_provider.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/models/question.dart';
import '../../../core/models/answer.dart';
import '../../../core/utils/app_utils.dart';
import '../../../core/widgets/transgression_reporting_portal.dart';
import '../../../core/routes/app_router.dart';

class QuestionAnswerPage extends StatefulWidget {
  final DiscussionTopic topic;

  const QuestionAnswerPage({super.key, required this.topic});

  @override
  State<QuestionAnswerPage> createState() => _QuestionAnswerPageState();
}

class _QuestionAnswerPageState extends State<QuestionAnswerPage> {
  final TextEditingController _answerController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _answerController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/answer-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildAppBar(),
              _buildQuestionSection(),
              Expanded(child: _buildAnswersSection()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, color: Colors.black, size: 24.w),
          ),
          const Spacer(),
          GestureDetector(
            onTap: _handleQuestionReport,
            child: Icon(MyIcons.iconReport, color: Colors.black, size: 24.w),
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 20.h),
      child: Hero(
        tag: 'question_title_${widget.topic.topicId}',
        child: Material(
          color: Colors.transparent,
          child: Text(
            widget.topic.topicTitle,
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black,
              fontFamily: 'Poppins',
              height: 1.3,
            ),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }

  Widget _buildAnswersSection() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF6F6253),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Column(
        children: [
          Expanded(
            child: Consumer<DiscussionHubProvider>(
              builder: (context, discussionProvider, child) {
                final currentTopic = discussionProvider.topicCollection
                    .firstWhere(
                      (topic) => topic.topicId == widget.topic.topicId,
                      orElse: () => widget.topic,
                    );

                if (currentTopic.responseList.isEmpty) {
                  return _buildEmptyState();
                }

                return ListView.builder(
                  controller: _scrollController,
                  padding: EdgeInsets.all(16.w),
                  itemCount: currentTopic.responseList.length,
                  itemBuilder: (context, index) {
                    return _buildAnswerItem(currentTopic.responseList[index]);
                  },
                );
              },
            ),
          ),
          _buildInputSection(),
        ],
      ),
    );
  }

  Widget _buildAnswerItem(ResponseItem response) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () => _navigateToResponseUserProfile(response.contributorId),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: _getImageProvider(response.contributorProfileImage),
                  fit: BoxFit.cover,
                ),
                border: Border.all(color: Colors.white, width: 1.w),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      response.contributorDisplayName,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                        fontFamily: 'Poppins',
                      ),
                    ),
                    const Spacer(),
                  ],
                ),
                SizedBox(height: 4.h),
                Text(
                  _formatTimeAgo(response.publishedTime),
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white.withValues(alpha: 0.7),
                    fontFamily: 'Poppins',
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  response.responseText,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                    fontFamily: 'Poppins',
                    height: 1.4,
                  ),
                ),
              ],
            ),
          ),
          GestureDetector(
            onTap: () => _showReportDialog(response),
            child: Icon(
              MyIcons.iconReport2,
              size: 22.w,
              color: Colors.white.withValues(alpha: 0.7),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            constraints: BoxConstraints(maxWidth: 126.w, maxHeight: 118.h),
            child: Image.asset('assets/images/empty.png', fit: BoxFit.contain),
          ),

          SizedBox(height: 24.h),

          Text(
            'No One Has Answered Yet. Be\nThe First To Help Solve The\nProblem!',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w700,
              height: 1.4,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInputSection() {
    return Consumer<GlobalStateCoordinator>(
      builder: (context, coordinator, child) {
        final isLoggedIn = coordinator.isLoggedIn;
        final currentUser = coordinator.currentUser;

        return Container(
          padding: EdgeInsets.all(16.w),
          child: Row(
            children: [
              Container(
                width: 45.w,
                height: 45.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: isLoggedIn ? null : Colors.grey[300],
                  image:
                      isLoggedIn && currentUser?.avatar.isNotEmpty == true
                          ? DecorationImage(
                            image: _getImageProvider(currentUser!.avatar),
                            fit: BoxFit.cover,
                          )
                          : null,
                ),
                child:
                    !isLoggedIn
                        ? Icon(
                          Icons.person,
                          color: Colors.grey[600],
                          size: 20.w,
                        )
                        : null,
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white.withValues(alpha: 0.9),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          controller: _answerController,
                          decoration: InputDecoration(
                            hintText: 'Say Something',
                            hintStyle: TextStyle(
                              color: Colors.grey[500],
                              fontSize: 14.sp,
                              fontFamily: 'Poppins',
                            ),
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 12.h,
                            ),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => _handleSendTap(isLoggedIn),
                        child: Container(
                          margin: EdgeInsets.all(4.w),
                          padding: EdgeInsets.all(10.w),
                          decoration: const BoxDecoration(
                            color: Color(0xFFCD8B76),
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: Icon(
                              MyIcons.iconSend,
                              color: Colors.white,
                              size: 16.w,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  String _formatTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }

  ImageProvider _getImageProvider(String imagePath) {
    if (imagePath.isEmpty) {
      return const AssetImage('assets/images/avatar1.png');
    }

    if (imagePath.startsWith('assets/')) {
      return AssetImage(imagePath);
    }

    if (imagePath.startsWith('/') || imagePath.contains('\\')) {
      final file = File(imagePath);
      if (file.existsSync()) {
        return FileImage(file);
      }
    }

    if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
      return NetworkImage(imagePath);
    }

    return AssetImage(imagePath);
  }

  void _handleSendTap(bool isLoggedIn) {
    if (_answerController.text.trim().isEmpty) return;

    if (!isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to post an answer',
        title: 'Login Required',
        onLogin: () {
          Navigator.of(context).pushNamed('/login');
        },
      );
      return;
    }

    _submitAnswer();
  }

  void _showReportDialog(ResponseItem response) {
    _reportAnswer(response);
  }

  void _reportAnswer(ResponseItem response) {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: response.responseId,
      targetType: 'answer',
      onReportSubmitted: (transgression) {
        // 举报成功后删除对应的回答
        _deleteReportedResponse(response);
      },
    );
  }

  /// 删除被举报的回答
  void _deleteReportedResponse(ResponseItem response) {
    final discussionProvider = context.read<DiscussionHubProvider>();
    discussionProvider.deleteResponse(
      widget.topic.topicId,
      response.responseId,
    );
  }

  /// 导航到回答用户主页
  void _navigateToResponseUserProfile(String userId) {
    final coordinator = context.read<GlobalStateCoordinator>();
    final currentUser = coordinator.currentUser;

    // 如果点击的是自己的头像，不跳转
    if (currentUser != null && currentUser.id == userId) {
      return;
    }

    // 跳转到他人用户页面
    Navigator.pushNamed(context, AppRouter.otherUser, arguments: userId);
  }

  void _handleQuestionReport() {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: widget.topic.topicId,
      targetType: 'discussion_topic',
      onReportSubmitted: (transgression) {
        _deleteTopicAndGoBack();
      },
    );
  }

  void _deleteTopicAndGoBack() {
    final discussionProvider = context.read<DiscussionHubProvider>();
    discussionProvider.deleteTopic(widget.topic.topicId);

    Navigator.of(context).pop(true);
  }

  void _submitAnswer() async {
    if (_answerController.text.trim().isEmpty) return;

    final coordinator = context.read<GlobalStateCoordinator>();
    final discussionProvider = context.read<DiscussionHubProvider>();
    final currentUser = coordinator.currentUser;

    if (currentUser != null) {
      await discussionProvider.addResponseToTopic(
        topicId: widget.topic.topicId,
        responseText: _answerController.text.trim(),
        contributorId: currentUser.id,
        contributorName: currentUser.userName,
        contributorAvatar: currentUser.avatar,
      );

      _answerController.clear();

      Future.delayed(const Duration(milliseconds: 200), () {
        if (_scrollController.hasClients) {
          _scrollController.animateTo(
            _scrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      });
    }
  }
}
